package com.lyj.controller;

import cn.hutool.http.HttpResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyj.pojo.Document;
import com.lyj.pojo.LayuiPage;
import com.lyj.pojo.User;
import com.lyj.service.DocumentService;
import com.lyj.service.UserService;
import com.lyj.util.LayuiData;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.tagext.PageData;
import java.io.*;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/document")
public class DocumentController {

    @Autowired
    private DocumentService documentService;
    @Autowired
    private UserService userService;

    //上传文件保存路径
//    private static final String PATH = "D:\\yueqian\\HRM\\web\\file";

    @RequestMapping("/list.html")
    public ModelAndView toList(ModelAndView mv) {
        mv.setViewName("documentList");
        mv.addObject("users", userService.findAllUser(new User()));

        return mv;
    }

    @RequestMapping("/addDocument.html")
    public ModelAndView toAdd(ModelAndView mv) {
        mv.setViewName("addDocument");
        return mv;
    }

    @RequestMapping("/list")
    public ResponseEntity list(LayuiPage layuiPage, Document document) {
        PageHelper.startPage(layuiPage.getPage(), layuiPage.getLimit());
        List<Document> documents = documentService.findAllDocument(document);
        for (Document document1 : documents) {
            User user = userService.findUserById(document1.getUserId());
            document1.setUserName(user.getUserName());
        }
        return ResponseEntity.ok(LayuiData.toLayuiTableModel(new PageInfo(documents)));
    }

    @RequestMapping("/upload")
    public ResponseEntity uploadAndAddDoc(MultipartFile file, Document document, HttpSession session) {
        document.setFileType(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));
        document.setFileName(file.getOriginalFilename());
        document.setFileSize(file.getSize());

        String path = session.getServletContext().getRealPath("file");
        File uploadFile = new File(path, file.getOriginalFilename());
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.ok(LayuiData.toLayuiUploadError(1, "服务器异常，文档上传失败"));
        }

        documentService.addDocument(document);

        return ResponseEntity.ok(LayuiData.toLayuiUploadSuccess(uploadFile.getAbsolutePath(),file.getOriginalFilename()));
    }


    @RequestMapping("/delete/{id}")
    public ResponseEntity deleteDocumentById(@PathVariable Integer id, HttpSession session) {
        Document document = documentService.findDocumentById(id);
        String fileName = document.getFileName();
        documentService.deleteDocumentById(id);
        String path = session.getServletContext().getRealPath("file");
        File file = new File(path, fileName);
        if (file.exists()) {
            file.delete();
        }
        return ResponseEntity.ok(LayuiData.success());
    }

    @RequestMapping("/download")
    public ResponseEntity download(String fileName, HttpSession session, HttpServletResponse response) {
        response.setContentType("application/x-msdownload");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String(fileName.getBytes("UTF-8"), "ISO8859-1"));

            String path = session.getServletContext().getRealPath("file");
            File downloadFile = new File(path, fileName);
            if (downloadFile.exists()) {
                long fileLength = downloadFile.length();
                response.setHeader("Content-Length", String.valueOf(fileLength));
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadFile));
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
                bis.close();
                bos.close();
            } else {
                return ResponseEntity.ok(LayuiData.error(500, "没找到该文件"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(LayuiData.success());
    }

//    @RequestMapping("/getFileUrl")
//    public ResponseEntity getFileUrlByFileName(String fileName,HttpSession session){
////        String realPath = session.getServletContext().getRealPath("file");
//        File file = new File(PATH,fileName);
//        if (file.exists()){
//            String absolutePath = file.getAbsolutePath();
//            System.out.println(absolutePath);
//            return ResponseEntity.ok(LayuiData.success(absolutePath));
//        }else{
//            return ResponseEntity.ok(LayuiData.error(500,"文件不存在"));
//        }
//    }
}
